<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" :disabled="disabled" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled || isFlow"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="责改号" prop="rectifyNo">
            <el-input v-model="formData.rectifyNo" disabled placeholder="请输入责改号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="被复核单位" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入被复核单位" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法定代表人" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="position">
            <el-input v-model="formData.position" disabled placeholder="请输入职务" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" disabled placeholder="请输入电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="formData.unifiedSocialCreditCode" disabled placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮编" prop="postalCode">
            <el-input v-model="formData.postalCode" disabled placeholder="请输入邮编" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
            <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="事由" prop="reasonDesc">
            <el-input v-model="formData.reasonDesc" placeholder="请输入事由" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="检查人" prop="inspectorId1">
            <el-select
              v-model="formData.inspectorId1"
              clearable
              filterable
              placeholder="请输入"
              @change="handlepartyChange1">
              <el-option
                v-for="item in inspectorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执法证编号" prop="inspectorCertNo1">
            <el-input v-model="formData.inspectorCertNo1" disabled placeholder="请输入执法证编号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="检查人" prop="inspectorId2">
            <el-select
              v-model="formData.inspectorId2"
              clearable
              filterable
              placeholder="请输入"
              @change="handlepartyChange2">
              <el-option
                v-for="item in inspectorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执法证编号" prop="inspectorCertNo2">
            <el-input v-model="formData.inspectorCertNo2" disabled placeholder="请输入执法证编号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="记录人" prop="recorderName">
            <el-select
              v-model="formData.recorderId"
              clearable
              filterable
              placeholder="请选择记录人"
              @change="handlepartyChange3">
              <el-option
                v-for="(item, index) in inspectorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执法证编号" prop="recorderCertNo">
            <el-input v-model="formData.recorderCertNo" disabled placeholder="请输入执法证编号" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="复核时间" prop="daterangeApplyTime" :style="{ width: '94%' }">
            <el-date-picker
              clearable
              v-model="daterangeApplyTime"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="现场复核地点" :rules="rules.addressObj2" prop="addressObj2">
            <locationSelect v-model="formData.addressObj2" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="现场负责人姓名" prop="sitePrincipalName">
            <el-input v-model="formData.sitePrincipalName" disabled placeholder="请输入现场负责人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="现场负责人电话" prop="sitePrincipalPhone">
            <el-input v-model="formData.sitePrincipalPhone" disabled placeholder="请输入现场负责人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="公民身份证号码" prop="sitePrincipalIdNo">
            <el-input v-model="formData.sitePrincipalIdNo" disabled placeholder="请输入公民身份证号码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作单位" prop="sitePrincipalWorkUnit">
            <el-input v-model="formData.sitePrincipalWorkUnit" disabled placeholder="请输入工作单位" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="现场负责人职务" prop="sitePrincipalJob">
            <el-input v-model="formData.sitePrincipalJob" disabled placeholder="请输入现场负责人职务" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="现场复核说明" prop="recheckSubject">
            <SmartTextInput
              v-model="formData.recheckSubject"
              type="textarea"
              :rows="4"
              placeholder="请输入现场复核说明，输入关键词后按Tab键快速补全"
              :min-length="2"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="现场复核情况" prop="recheckContent">
            <SmartTextInput
              v-model="formData.recheckContent"
              type="textarea"
              :rows="4"
              placeholder="请输入现场复核情况，输入关键词后按Tab键快速补全"
              :min-length="2"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form-title-wrapper">
      <div class="form-title-text">现场复核照片</div>
    </div>
    <imgGroup ref="imgGroupRef" :id="id" :formData="formData" :disabled="disabled" />
    <label class="el-form-item__label" style="font-size: 14px">是否上传附件</label>
    <el-radio-group v-model="formData.isFile" :disabled="disabled">
      <el-radio label="0" size="large">否</el-radio>
      <el-radio label="1" size="large">是</el-radio>
    </el-radio-group>
    <!-- 附件 -->
    <FileList v-if="formData.isFile === '1'" :disabled="disabled" :fileUploadList="formData.tsiteRecheckFilesList" />
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch, onBeforeUnmount } from 'vue'
import {
  getSiterecheck,
  addSiterecheck,
  updateSiterecheck,
  getCaseList,
  getContent,
  previewPdf,
} from '@/api/onSiteReview/index.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { getUserEnforcementNo } from '@/api/system/user.js'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import { useRouter } from 'vue-router'
import { commonRules } from '@/components/DynamicForm/config'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import imgGroup from './imgGroup.vue'
import FileList from '@/components/FileList/index.vue'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isFlow: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  rectifyNo: null,
  compulsoryRectifyId: null,
  partyName: null,
  streetOfCompanyAddress: null,
  address: null,
  unifiedSocialCreditCode: null,
  legalRepresentative: null,
  position: null,
  contactPhone: null,
  postalCode: null,
  reasonDesc: null,
  sitePrincipalName: null,
  sitePrincipalJob: null,
  sitePrincipalPhone: null,
  sitePrincipalIdNo: null,
  sitePrincipalWorkUnit: null,
  recheckSubject: null,
  recheckContent: null,
  ttsiteInspectionRecordPhotosList: [
    { groupName: '现场复核照片', evidenceTarget: null, photoTime: null, address: null, photos: null },
  ],
  isFile: '0',
  tsiteRecheckFilesList: [],
})
const daterangeApplyTime = ref([])

// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地点'))
  } else {
    callback()
  }
}
const validateTime = (rule, value, callback) => {
  if (!daterangeApplyTime.value || daterangeApplyTime.value.length !== 2) {
    callback(new Error('请选择复核时间'))
  } else {
    // 验证是否是同一天
    const startDate = new Date(daterangeApplyTime.value[0])
    const endDate = new Date(daterangeApplyTime.value[1])

    const isSameDay =
      startDate.getFullYear() === endDate.getFullYear() &&
      startDate.getMonth() === endDate.getMonth() &&
      startDate.getDate() === endDate.getDate()

    if (!isSameDay) {
      callback(new Error('复核时间不能跨天'))
    } else if (startDate.getTime() >= endDate.getTime()) {
      callback(new Error('结束时间必须大于开始时间'))
    } else {
      callback()
    }
  }
}
// Form validation rules
const rules = {
  caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  rectifyNo: [{ required: true, message: '责改号不能为空', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  position: [{ required: true, message: '职务不能为空', trigger: ['blur', 'change'] }],
  contactPhone: [commonRules.phone],
  postalCode: [{ required: true, message: '邮编不能为空', trigger: ['blur', 'change'] }],
  reasonDesc: [{ required: true, message: '事由不能为空', trigger: ['blur', 'change'] }],
  daterangeApplyTime: [{ required: true, validator: validateTime, trigger: ['blur', 'change'] }],
  sitePrincipalName: [{ required: true, message: '现场负责人姓名不能为空', trigger: ['blur', 'change'] }],
  sitePrincipalJob: [{ required: true, message: '现场负责人职务不能为空', trigger: ['blur', 'change'] }],
  sitePrincipalPhone: [commonRules.phone],
  sitePrincipalIdNo: [commonRules.identityCard],
  sitePrincipalWorkUnit: [{ required: true, message: '工作单位不能为空', trigger: ['blur', 'change'] }],
  recheckSubject: [{ required: true, message: '现场复核说明不能为空', trigger: ['blur', 'change'] }],
  recheckContent: [{ required: true, message: '现场复核情况不能为空', trigger: ['blur', 'change'] }],
  businessType: [{ required: true, message: '营业执照类型不能为空', trigger: ['blur', 'change'] }],
  unifiedSocialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  addressObj2: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  inspectorId1: [{ required: true, message: '检查人不能为空', trigger: ['blur', 'change'] }],
  inspectorCertNo1: [{ required: true, message: '执法证编号不能为空', trigger: ['blur', 'change'] }],
  inspectorId2: [{ required: true, message: '检查人不能为空', trigger: ['blur', 'change'] }],
  inspectorCertNo2: [{ required: true, message: '执法证编号不能为空', trigger: ['blur', 'change'] }],
  recorderName: [{ required: true, message: '记录人不能为空', trigger: ['blur', 'change'] }],
  recorderCertNo: [{ required: true, message: '执法证编号不能为空', trigger: ['blur', 'change'] }],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    rectifyNo: null,
    compulsoryRectifyId: null,
    partyName: null,
    streetOfCompanyAddress: null,
    address: null,
    unifiedSocialCreditCode: null,
    legalRepresentative: null,
    inspectorId1: null,
    inspectorName1: null,
    inspectorCertNo1: null,
    inspectorId2: null,
    inspectorName2: null,
    inspectorCertNo2: null,
    recorderName: null,
    recorderCertNo: null,
    position: null,
    contactPhone: null,
    postalCode: null,
    reasonDesc: null,
    sitePrincipalName: null,
    sitePrincipalJob: null,
    sitePrincipalPhone: null,
    sitePrincipalIdNo: null,
    sitePrincipalWorkUnit: null,
    recheckSubject: null,
    recheckContent: null,
    ttsiteInspectionRecordPhotosList: [
      { groupName: '现场复核照片', evidenceTarget: null, photoTime: null, address: null, photos: null },
    ],
    isFile: '0',
    tsiteRecheckFilesList: [],
  }
  proxy.resetForm('noticedemandapprovalRef')
  daterangeApplyTime.value = []
}

const inspectorOptions = ref([])
const getUserList = async () => {
  const res = await getUserEnforcementNo({})
  if (res.data.length > 0) {
    inspectorOptions.value = res.data.map(item => {
      return { value: item.userId, label: item.name, enforcementNo: item.enforcementNo }
    })
  }
}
getUserList()
const handlepartyChange1 = val => {
  if (val === formData.value.inspectorId2) {
    formData.value.inspectorName1 = undefined
    formData.value.inspectorCertNo1 = undefined
    formData.value.inspectorId1 = undefined
    return
  }
  inspectorOptions.value.forEach(item => {
    if (item.value === val) {
      formData.value.inspectorName1 = item.label
      formData.value.inspectorCertNo1 = item.enforcementNo
    }
  })
}
const handlepartyChange2 = val => {
  if (val === formData.value.inspectorId1) {
    formData.value.inspectorName2 = undefined
    formData.value.inspectorCertNo2 = undefined
    formData.value.inspectorId2 = undefined
    return
  }
  inspectorOptions.value.forEach(item => {
    if (item.value === val) {
      formData.value.inspectorName2 = item.label
      formData.value.inspectorCertNo2 = item.enforcementNo
    }
  })
}
const handlepartyChange3 = val => {
  inspectorOptions.value.forEach(item => {
    if (item.value === val) {
      formData.value.recorderName = item.label
      formData.value.recorderCertNo = item.enforcementNo
    }
  })
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getSiterecheck(id)
      if (!res?.data) return
      formData.value = res.data
      formData.value.addressObj = {
        photoLocation: res.data.address,
        streetOfPhotoLocation: res.data.streetOfCompanyAddress,
      }
      formData.value.addressObj2 = {
        photoLocation: res.data.recheckAddress,
        streetOfPhotoLocation: res.data.streetOfRecheckAddress,
      }
      daterangeApplyTime.value = [res.data.recheckStartTime, res.data.recheckEndTime]
      formData.value.ttsiteInspectionRecordPhotosList = [
        {
          address: {
            photoLocation: res.data.tSiteRecheckPhotos.photoLocation,
            streetOfPhotoLocation: res.data.tSiteRecheckPhotos.streetOfPhotoLocation,
          },
          groupName: res.data.tSiteRecheckPhotos.groupName,
          evidenceTarget: res.data.tSiteRecheckPhotos.evidenceTarget,
          photoTime: res.data.tSiteRecheckPhotos.photoTime,
          photos: res.data.tSiteRecheckPhotos.photos,
          id: res.data.id,
        },
      ]
      formData.value.isFile = res.data.tsiteRecheckFilesList && res.data.tsiteRecheckFilesList.length > 0 ? '1' : '0'
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.rectifyNo = ''
      formData.value.compulsoryRectifyId = ''
      formData.value.partyName = ''
      formData.value.partyId = ''
      formData.value.legalRepresentative = ''
      formData.value.inspectorId1 = ''
      formData.value.inspectorName1 = ''
      formData.value.inspectorCertNo1 = ''
      formData.value.inspectorId2 = ''
      formData.value.inspectorName2 = ''
      formData.value.inspectorCertNo2 = ''
      formData.value.recorderName = ''
      formData.value.recorderCertNo = ''
      formData.value.position = ''
      formData.value.contactPhone = ''
      formData.value.postalCode = ''
      formData.value.reasonDesc = ''
      formData.value.sitePrincipalName = ''
      formData.value.sitePrincipalJob = ''
      formData.value.sitePrincipalPhone = ''
      formData.value.sitePrincipalIdNo = ''
      formData.value.sitePrincipalWorkUnit = ''
      formData.value.recheckSubject = ''
      formData.value.businessType = ''
      formData.value.unifiedSocialCreditCode = ''
      formData.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      formData.value.addressObj2 = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      return
    }
    const res = await registrationcaseDetail(val)
    const { partyName, partyId, legalRepresentative, unifiedSocialCreditCode, streetOfCompanyAddress, address } =
      res.data
    formData.value.caseNo = res.data.caseNo

    formData.value.partyName = partyName
    formData.value.partyId = partyId
    formData.value.legalRepresentative = legalRepresentative
    formData.value.position = res.data.position
    formData.value.contactPhone = res.data.contactPhone
    formData.value.postalCode = res.data.postalCode
    formData.value.sitePrincipalName = res.data.tSiteInspectionRecordList[0].sitePrincipalName
    formData.value.sitePrincipalJob = res.data.tSiteInspectionRecordList[0].sitePrincipalJob
    formData.value.sitePrincipalPhone = res.data.tSiteInspectionRecordList[0].sitePrincipalPhone
    formData.value.sitePrincipalIdNo = res.data.tSiteInspectionRecordList[0].sitePrincipalIdNo
    formData.value.sitePrincipalWorkUnit = res.data.tSiteInspectionRecordList[0].sitePrincipalWorkUnit
    formData.value.businessType = res.data.businessType
    formData.value.unifiedSocialCreditCode = unifiedSocialCreditCode
    formData.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    formData.value.legalRepresentative = res.data.legalRepresentative
    formData.value.inspectorId1 = res.data.inspectorId1
    formData.value.inspectorName1 = res.data.inspectorName1
    formData.value.inspectorCertNo1 = res.data.inspectorCertNo1
    formData.value.inspectorId2 = res.data.inspectorId2
    formData.value.inspectorName2 = res.data.inspectorName2
    formData.value.inspectorCertNo2 = res.data.inspectorCertNo2
    formData.value.recorderName = res.data.tSiteInspectionRecordList[0].recorderName
    formData.value.recorderCertNo = res.data.tSiteInspectionRecordList[0].recorderCertNo
    const res2 = await getContent(val)
    formData.value.rectifyNo = res2.data.rectifyNo
    formData.value.compulsoryRectifyId = res2.data.compulsoryRectifyId
    formData.value.reasonDesc = res2.data.reasonDesc
    formData.value.addressObj2 = {
      photoLocation: res2.data.recheckAddress,
      streetOfPhotoLocation: res2.data.streetOfRecheckAddress,
    }
    formData.value.recheckSubject = res2.data.recheckSubject

    resolve()
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const imgGroupRef = ref()
const submitForm = (isPreview = false) => {
  return new Promise((resolve, reject) => {
    Promise.all([noticedemandapprovalRef.value.validate(), imgGroupRef.value.validateForm()])
      .then(async valid => {
        if (valid[0] && valid[1]) {
          const params = JSON.parse(JSON.stringify(formData.value))
          if (daterangeApplyTime.value.length === 2) {
            params.recheckStartTime = daterangeApplyTime.value[0]
            params.recheckEndTime = daterangeApplyTime.value[1]
          } else {
            params.recheckStartTime = null
            params.recheckEndTime = null
          }
          params.address = params.addressObj.photoLocation
          params.streetOfCompanyAddress = params.addressObj.streetOfPhotoLocation
          params.recheckAddress = params.addressObj2.photoLocation
          params.streetOfRecheckAddress = params.addressObj2.streetOfPhotoLocation
          params.tSiteRecheckPhotos = params.ttsiteInspectionRecordPhotosList[0]
          params.tSiteRecheckPhotos.photoLocation = params.ttsiteInspectionRecordPhotosList[0].address.photoLocation
          params.tSiteRecheckPhotos.streetOfPhotoLocation =
            params.ttsiteInspectionRecordPhotosList[0].address.streetOfPhotoLocation
          delete params.tSiteRecheckPhotos.address
          delete params.addressObj
          delete params.addressObj2
          delete params.ttsiteInspectionRecordPhotosList
          if (isPreview === true) {
            resolve(params)
            return
          }
          let result = null
          if (params.id) {
            result = updateSiterecheck
          } else {
            result = addSiterecheck
          }
          console.log(params)
          await result(params)
          ElMessage.success('提交成功')
          emit('handleSubmit', result)
        }
      })
      .catch(err => {
        console.log('验证失败', err)
        reject(false)
      })
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
onBeforeUnmount(() => {})
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
